﻿using Hsp.Novels.Model;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.IO;

namespace NetCore.SqlSugar.Orm
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello SqlSugar!");

            //IConfigurationRoot _configuration = new ConfigurationBuilder()
            //.SetBasePath(Directory.GetCurrentDirectory())
            //.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            //.Build();

            //string sqlConnectionString = ConfigurationExtensions.GetConnectionString(_configuration, "DBConnectionString");

            var builder = WebApplication.CreateBuilder(args);
            var config = builder.Configuration;
            var connectionString = config.GetConnectionString("DBConnectionString");

            string sqlConnectionString = connectionString;

            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConfigId = "0",
                ConnectionString = sqlConnectionString,
                IsAutoCloseConnection = true,
                DbType = DbType.SqlServer
            };

            {
                //Creaate database object
                SqlSugarClient db = new(new ConnectionConfig() { ConfigId = "0", DbType = DbType.SqlServer, ConnectionString = sqlConnectionString, IsAutoCloseConnection = true });


                var abc = db.Queryable<Chapters>().ToList();
                var def = abc;
            }


            {
                ////Creaate database object
                //SqlSugarClient db = new(new ConnectionConfig() { ConfigId = "0", DbType = DbType.SqlServer, ConnectionString = sqlConnectionString, IsAutoCloseConnection = true });


                //// 6.格式化类名和属性名
                //foreach (var item in db.DbMaintenance.GetTableInfoList())
                //{
                //    string entityName = item.Name;/*实体名驼峰*/
                //    db.MappingTables.Add(entityName, item.Name);
                //    foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
                //    {
                //        db.MappingColumns.Add(GetEntityName(col.DbColumnName) /*类的属性驼峰*/, col.DbColumnName, entityName);
                //        Console.Write(".");
                //    }
                //}

                //db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\Codes\Hsp.WebNovels\NetCore.SqlSugar.Orm\Models", "Hsp.Novels.Model");
            }

            {
                //CodeFirst - 实体类生成表
                //代码先行，先有代码，然后有数据库，只关注业务，业务中的对象如果需要就直接创建实体，对应的数
                //据库表，由代码一次生成；

                //using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
                //{
                //    //如果不存在创建数据库存在不会重复创建 
                //    {
                //        db.DbMaintenance.CreateDatabase(); // 注意 ：Oracle和个别国产库需不支持该方法，需要手动建库  
                //    }
                //    //创建表根据实体类CodeFirstTable1     
                //    {
                //        db.CodeFirst.InitTables(typeof(WebSites));//这样一个表就能成功创建了
                //        db.CodeFirst.InitTables(typeof(Novels));//这样一个表就能成功创建了
                //        db.CodeFirst.InitTables(typeof(Chapters));//这样一个表就能成功创建了
                //        db.CodeFirst.InitTables(typeof(ReplaceTb));//这样一个表就能成功创建了
                //    }
                //}

            }

            Console.WriteLine("Bye SqlSugar!");
            Console.ReadKey();
        }


        /// <summary>
        /// 获取表字段修正后的名称
        /// </summary>
        /// <param name="columnName">字段名称</param>
        /// <returns></returns>
        private static string GetEntityName(string columnName)
        {
            var name = columnName;
            if (name.IndexOf("_") > -1)
            {
                name = string.Empty;
                var arr = columnName.Split('_');
                foreach (string s in arr)
                {
                    name += ToUpperFirst(s, 1);
                }
            }
            else
            {
                name = ToUpperFirst(name, 0);
            }
            return name;
        }

        /// <summary>
        /// 字符串首字符大写
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="change">是否预先变更为小写：0-否；1-是；</param>
        /// <returns></returns>
        private static string ToUpperFirst(string str, int change)
        {
            if (string.IsNullOrEmpty(str)) return "";

            //if (str.ToLower() == "qq") str = "Qq";
            //if (str.ToLower() == "id") str = "Id";
            //if (str.ToLower() == "pid") str = "Pid";
            //if (str.Contains("QQ")) str = str.Replace("QQ", "Qq");
            //if (str.Contains("ID")) str = str.Replace("ID", "Id");
            //if (str.Contains("API")) str = str.Replace("API", "Api");

            if (change == 1) str = str.ToLower();
            char[] a = str.ToCharArray();
            a[0] = char.ToUpper(a[0]);
            return new string(a);
        }
    }

    //public class CodeFirstTable1
    //{
    //    [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
    //    public int Id { get; set; }

    //    public string? Name { get; set; }
    //    [SugarColumn(ColumnDataType = "Nvarchar(255)")]//自定格式的情况 length不要设置
    //    public string? Text { get; set; }
    //    [SugarColumn(IsNullable = true)]//可以为NULL
    //    public DateTime CreateTime { get; set; }
    //}




}
